﻿#!/usr/bin/python3
# -*- coding: utf-8 -*-
import mysql.connector
import config
import sys
import os
import csv
config = config.Config.dbinfo().copy()
colnames = "lokallag, lokalnavn, kategori, mdl_nummer, mdl_kat, navn, adresse, dato_kont, fodselsdato, tlf_priv, tlf_arb, tlf_mob, epost, poststed"

if (not len(sys.argv) > 1):
	sys.exit("Spesifiser hvilken fil du vil importere")

#Converter inputfila fra utf-16 til utf-8
os.system("iconv -f utf-16 -t utf-8 "+ sys.argv[1] +"> .temp.csv")

#åpne den konverterte csv-fila
#csv = open('temp.csv', 'r')
reader = csv.reader(open('.temp.csv', 'r'))

#Koble til databasen
db = mysql.connector.Connect(**config)
cursor = db.cursor()
#Slett gamle data
cursor.execute("DELETE FROM sentral")

count = 0
for row in reader:
	if(count == 1):
		row = str(row)
		row = row.replace("[", "")
		row = row.replace("]", "")
		sql = "INSERT INTO sentral ("+ colnames +") VALUES ("+ row +")"
		print(sql)
		cursor.execute(sql)
		db.commit()
	else:
		count = 1

#Steng databasen
db.close()

#Slett tempfila
os.system("rm -rf .temp.csv")
